package com.henghai.zhenxuan.ui.page.mall;

import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.henghai.zhenxuan.BR;
import com.henghai.zhenxuan.data.api.ConversionProductApi;
import com.henghai.zhenxuan.data.bean.AddressBean;
import com.henghai.zhenxuan.data.bean.ProductInfoBean;
import com.henghai.zhenxuan.domain.request.AddressListRequester;
import com.henghai.zhenxuan.domain.request.ConversionProductRequester;
import com.henghai.zhenxuan.domain.request.ProductInfoRequester;
import com.henghai.zhenxuan.domain.request.PurchaseProductRequester;
import com.henghai.zhenxuan.pay.OnSuccessAndErrorListener;
import com.henghai.zhenxuan.pay.PayManager;
import com.henghai.zhenxuan.pay.PayType;
import com.henghai.zhenxuan.ui.page.adapter.ProductImageListAdapter;
import com.henghai.zhenxuan.ui.view.AddEditingDialogFragment;
import com.henghai.zhenxuan.utils.ListFilterHelper;
import com.henghai.zhenxuan.R;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kunminx.architecture.ui.page.BaseFragment;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.ui.state.State;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;

public class CommodityFragment extends BaseFragment {
    public static final String KEY = "productId";
    private CommodityStates mStates;
    private ProductInfoRequester mProductInfoRequester;
    private ConversionProductRequester mConversionProductRequester;
    private AddressBean mAddress;
    private AddressListRequester mAddressListRequester;
    private ProductImageListAdapter mAdapter;
    private PurchaseProductRequester mPurchaseProductRequester;
    private String productId;


    @Override
    protected void initViewModel() {
        mProductInfoRequester = getFragmentScopeViewModel(ProductInfoRequester.class);
        mStates = getFragmentScopeViewModel(CommodityStates.class);
        mConversionProductRequester = getFragmentScopeViewModel(ConversionProductRequester.class);
        mPurchaseProductRequester = getFragmentScopeViewModel(PurchaseProductRequester.class);
        mAddressListRequester = getFragmentScopeViewModel(AddressListRequester.class);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getArguments();
        productId = bundle != null ? bundle.getString(KEY, "") : "";
        boolean isOrder = bundle.getBoolean("isOrder", false);
        mStates.isOrder.set(isOrder);
        WaitDialog dialog = WaitDialog.show("正在加载").setOnBackPressedListener(waitDialog -> {
            waitDialog.doDismiss();
            return false;
        });
        Banner banner = view.findViewById(R.id.commodity_im);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);


        // 设置宽度和高度的比例，例如：16:9
        int width = displayMetrics.widthPixels; // 获取Banner的宽度
        //int height = width; // 根据比例计算高度
        // 设置宽度和高度
        ViewGroup.LayoutParams params = banner.getLayoutParams();
        params.width = width;
        params.height = width;
        banner.setLayoutParams(params);
        mProductInfoRequester.getProductInfoResult().observe(this, httpBeanDataResult -> {
            if (dialog.isShow()) {
                WaitDialog.dismiss();
            }
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }

            mStates.productInfoBean.set(httpBeanDataResult.getResult().getData());
            mStates.mainList.set(ListFilterHelper.filterItem(mStates.productInfoBean.get().getProductFileList(), item -> item.getFileType().equals("1")));
            mStates.loseList.set(ListFilterHelper.filterItem(mStates.productInfoBean.get().getProductFileList(), item -> item.getFileType().equals("2")));
        });
        mProductInfoRequester.requestProductInfo(this, productId);

        mAddressListRequester.getResult().observe(this, httpBeanDataResult -> {
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            if (!httpBeanDataResult.getResult().getData().getRows().isEmpty()) {
                mAddress = httpBeanDataResult.getResult().getData().getRows().get(0);
            }
        });
        //获取收货地址列表
        mAddressListRequester.request(this);
        //商品兑换结果
        mConversionProductRequester.getResult().observe(this, httpBeanDataResult -> {
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            TipDialog.show(getActivity().getString(R.string.paymentsuccessful), WaitDialog.TYPE.SUCCESS);
            mProductInfoRequester.requestProductInfo(getViewLifecycleOwner(), productId);
        });

        mPurchaseProductRequester.getResult().observe(this, httpBeanDataResult -> {
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            PayManager.getPayManager(PayType.ALIPAY).pay(getActivity(), httpBeanDataResult.getResult().getMsg(), new OnSuccessAndErrorListener() {
                @Override
                public void onSuccess(@Nullable String s) {
                    TipDialog.show(s, WaitDialog.TYPE.SUCCESS);
                    mProductInfoRequester.requestProductInfo(getViewLifecycleOwner(), productId);
                }

                @Override
                public void onError(@Nullable String s) {
                    TipDialog.show(s, WaitDialog.TYPE.ERROR);
                }
            });
        });
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        mAdapter = new ProductImageListAdapter(getContext());
        return new DataBindingConfig(R.layout.fragment_commodity, BR.vm, mStates).addBindingParam(BR.listener,
                new ListenerHandler()).addBindingParam(BR.click, new CommodityFragment.ClickProxy()).addBindingParam(BR.adapter, mAdapter);
    }

    public class ClickProxy {
        public void address() {
            AddEditingDialogFragment.newInstance(mAddress).setOnItemBtClickListener(new AddEditingDialogFragment.OnItemBtClickListener() {
                @Override
                public void onEditClick() {
                    mAddressListRequester.request(getViewLifecycleOwner());
                }

                @Override
                public void onSaveClick(AddressBean addressBean) {
                    if (mAddress == null) {
                        mAddress = addressBean;
                    }
                    //获取收货地址列表
                    mAddressListRequester.request(getViewLifecycleOwner());
//                    if (mAddress.getId() < 1) {
//                        return;
//                    }
                    if (mAddress == null ||
                            mAddress.getConsigneeAddress() == null ||
                            mAddress.getConsigneeAddress().isEmpty() ||
                            mAddress.getConsigneeName() == null ||
                            mAddress.getConsigneeName().isEmpty() ||
                            mAddress.getConsigneePhone() == null ||
                            mAddress.getConsigneePhone().isEmpty()) {
                        TipDialog.show("请完善收货地址信息");
                        return;
                    }
//                    if (mStates.productInfoBean.get() != null && mStates.productInfoBean.get().getProductQuantity() != null) {
//                        if (Integer.parseInt(mStates.productInfoBean.get().getProductQuantity()) <= 0) {
//                            TipDialog.show("当前商品，没有库存了");
//                            return;
//                        }
//                    }

                    ArrayList<ConversionProductApi.ProductInfoBean> productInfoList = new ArrayList<>();
                    ConversionProductApi.ProductInfoBean productInfoBean = new ConversionProductApi.ProductInfoBean();
                    productInfoBean.setId(mStates.productInfoBean.get().getId() + "");
                    productInfoBean.setProductQuantity("1");
                    productInfoList.add(productInfoBean);
                    mConversionProductRequester.request(getViewLifecycleOwner(), mAddress.getId() + "", productInfoList);
//                    ArrayList<CharSequence> list = new ArrayList<>();
//                    list.add("支付宝");
////                    list.add("微信");
//                    BottomMenu.show(list)
//                            .setTitle("选择支付方式")
//                            .setOnMenuItemClickListener((dialog, text, index) -> {
//
//                                ArrayList<PurchaseProductApi.ProductInfoBean> productInfoList = new ArrayList<>();
//                                PurchaseProductApi.ProductInfoBean productInfoBean = new PurchaseProductApi.ProductInfoBean();
//                                productInfoBean.setId(mStates.productInfoBean.get().getId() + "");
//                                productInfoBean.setProductQuantity("1");
//                                productInfoList.add(productInfoBean);
//                                mPurchaseProductRequester.request(getViewLifecycleOwner(), mAddress.getUserId(), String.valueOf(index + 1), productInfoList);
//                                return false;
//                            });

                }
            }).show(getChildFragmentManager(), AddEditingDialogFragment.class.getSimpleName());

        }
    }

    public class ListenerHandler implements OnTitleBarListener {
        @Override
        public void onLeftClick(TitleBar titleBar) {
            OnTitleBarListener.super.onLeftClick(titleBar);
            nav().navigateUp();
        }

        @Override
        public void onRightClick(TitleBar titleBar) {
            OnTitleBarListener.super.onRightClick(titleBar);
        }
    }

    public static class CommodityStates extends StateHolder {
        public final State<ProductInfoBean> productInfoBean = new State<>(new ProductInfoBean());
        public final State<List<ProductInfoBean.ProductFileListBean>> mainList = new State<>(new ArrayList<>());
        public final State<List<ProductInfoBean.ProductFileListBean>> loseList = new State<>(new ArrayList<>());


        public final State<Boolean> isOrder = new State<>(false);
    }
}
